package com.letfox.ad.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.letfox.ad.model.UtilConstants;
import com.letfox.ad.service.ADReptRecordService;

@Component
public class ADUtil {
	
	@Autowired
	private ADReptRecordService adReptRecordService;
	private static ADUtil factory;
	
	/**
	 * 初始化静态工具类
	 */
	@PostConstruct
	public void init() {
		factory = this;
	}
	/**
	 * 字符串的压缩
	 * 
	 * @param str
	 *            待压缩的字符串
	 * @return 返回压缩后的字符串
	 * @throws IOException
	 */
	public static byte[] compress(String str) throws IOException {
		if (null == str || str.length() <= 0) {
			if (str == null || str.length() == 0) {
				return null;
			}
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip = new GZIPOutputStream(out);
		gzip.write(str.getBytes());
		gzip.close();
		System.out.println(out.toString());
		return out.toByteArray();
	}

	/**
	 * 字符串的解压
	 * 
	 * @param str
	 *            对字符串解压
	 * @return 返回解压缩后的字符串
	 * @throws IOException
	 */
	public static String unCompress(byte[] str) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(str);
		GZIPInputStream gunzip = new GZIPInputStream(in);
		byte[] buffer = new byte[256];
		int n;
		while ((n = gunzip.read(buffer)) >= 0) {
			out.write(buffer, 0, n);

		}
		// toString()使用平台默认编码，也可以显式的指定如toString(&quot;GBK&quot;)
		return out.toString("UTF-8");
	}

	public static byte[] compress(String str, String encoding) {
		if (str == null || str.length() == 0) {
			return null;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip;
		try {
			gzip = new GZIPOutputStream(out);
			gzip.write(str.getBytes(encoding));
			gzip.close();
		} catch (IOException e) {
			// ApiLogger.error("gzip compress error.", e);
		}
		return out.toByteArray();
	}

	// 解压缩
	public static String uncompress2(String str) throws IOException {
		if (str == null || str.length() == 0) {
			return str;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(
				str.getBytes("ISO-8859-1"));
		GZIPInputStream gunzip = new GZIPInputStream(in);
		byte[] buffer = new byte[256];
		int n;
		while ((n = gunzip.read(buffer)) >= 0) {
			out.write(buffer, 0, n);
		}
		return out.toString();
	}

	public static String compress2(String str) throws IOException {
		if (str == null || str.length() == 0) {
			return str;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip = new GZIPOutputStream(out);
		gzip.write(str.getBytes());
		gzip.close();
		return out.toString("ISO-8859-1");
	}

	public static String getRandomFileName(String name) {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		int i=(int) (+Math.random()*9999);
		String rename=((df.format(new Date())).replace("-","").replace(":", "").replace(" ", ""))+i;
		String[] strs= name.split("\\.");
	    String type=strs[1];
		String fileNamne=rename+"."+type;

		return fileNamne;// 当前时间
	}
	
	public static String getType(String type){
		if(type==null)
			return type;
		return Integer.parseInt(type)+1+"";
	} 
	public static Date repCheck(String request_id, String view_id) throws Exception{
		String decryResult=null;
		try {
			decryResult=new String(DESUtil.decrypt(DESUtil.parseHexStr2Byte(view_id), UtilConstants.SECRKEY));
			//打印数据
			System.out.println("时间戳解压后的数据: "+decryResult);
		} catch (Exception e) {
			//打印日志文件
			//.......
			throw new Exception("DES解析失败",e);
		}
		//对时间戳进行解析
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Long time=new Long(decryResult);
	    String d = format.format(time);
	    Date dateView=null;
	    try {
	    	dateView=format.parse(d);
	    	//打印数据
			System.out.println("时间戳data数据: "+dateView);
		} catch (Exception e) {
			//打印日志文件
			//.......
			throw new Exception("不是时间戳",e);
		}
	    return dateView;
	}
	/**
	 * 随机产生任意位数的字母+数字的组合字符串，n代表参数的位数
	 * @param n
	 * @return
	 */
	public static String getItemID(int n) {
		String val = "";
		Random random = new Random();
		for (int i = 0; i < n; i++) {
			String str = random.nextInt(2) % 2 == 0 ? "num" : "char";
			if ("char".equalsIgnoreCase(str)) { // 产生字母
				int nextInt = random.nextInt(2) % 2 == 0 ? 65 : 97;
				val += (char) (nextInt + random.nextInt(26));
			} else if ("num".equalsIgnoreCase(str)) { // 产生数字
				val += String.valueOf(random.nextInt(10));
			}
		}
		return val;
	}
	
	/**
	 * 生成request_id
	 * 生成规则为“RQ”+“年份”+13位时间戳+6位循环自增序列
	 * @return
	 */
	public static String getRequestId(){
		//初始值RQ
		StringBuffer stringBuffer=new StringBuffer("RQ");
		//查询序列
		String sequence=factory.adReptRecordService.selectSequence("ad_value");
		StringBuffer seqBuffer=new StringBuffer(sequence);
		for (int i = sequence.length(); i < 6 ; i++) {
			seqBuffer.insert(0,"0");
		}
		Calendar date = Calendar.getInstance();
		stringBuffer.append(String.valueOf(date.get(Calendar.YEAR))).append(date.getTimeInMillis()).append(seqBuffer);
		return stringBuffer.toString();
	}
	
	/**
	 * 用于生成AD_SCREEN_PLAN_ID，其组成是：SP+16位自增（不足补0）
	 * @return
	 */
	public static String getScreenSeqId(){
		//初始值SP
		StringBuffer stringBuffer=new StringBuffer("SP");
		//查询序列
		String sequence=factory.adReptRecordService.selectSequence("ad_screenplan_seq");
		StringBuffer seqBuffer=new StringBuffer(sequence);
		for (int i = sequence.length(); i < 16 ; i++) {
			seqBuffer.insert(0,"0");
		}
		stringBuffer.append(seqBuffer);
		return stringBuffer.toString();
	}
	
	/**
	 * (1)于生成AD_SCREEN_PLAN_ID，其组成是：SC+yyyymmdd（日期格式）+8位循环自增（不足补0）.
	 */
	public static String getPhysScreenID(){
		//生成日期
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd"); 
	    String dateString=dateFormat.format(date).toString().replaceAll("-", "");
		//初始值SP
		StringBuffer stringBuffer=new StringBuffer("SC"+dateString);
		//查询序列
		String sequence=factory.adReptRecordService.selectSequence("ad_physscreen_seq");
		StringBuffer seqBuffer=new StringBuffer(sequence);
		for (int i = sequence.length(); i < 8 ; i++) {
			seqBuffer.insert(0,"0");
		}
		stringBuffer.append(seqBuffer);
		return stringBuffer.toString();
	}
	
	
	/**
	 * 校验requestId
	 * @param requestId
	 * @return
	 */
	public static boolean checkRequestId(String requestId){
		boolean bool=true;
		String rq = requestId.substring(0, 2);
		String year = requestId.substring(2, 6);
		String time = requestId.substring(6, 19);
		String seq = requestId.substring(19);
		Calendar date = Calendar.getInstance();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (!rq.equals("RQ")) 
			bool=false;
		if (!year.equals(String.valueOf(date.get(Calendar.YEAR)))) 
			bool=false;
		try {
			Long lotime = new Long(time);
			String d = format.format(lotime);
			format.parse(d);
		} catch (Exception e) {
			bool=false;
		}
		try {
			Integer.parseInt(seq);
		} catch (Exception e) {
			bool=false;
		}
		if (!(seq.length() == 6))
			bool=false;
		return bool;
	}
	
	/**
	 * 获取访问接口者IP地址
	 * @param request
	 * @return
	 * @throws Exception
	 */
    public static String getIpAddr(HttpServletRequest request) {   
        String ip = request.getHeader("x-forwarded-for");   
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
            ip = request.getHeader("Proxy-Client-IP");   
        }   
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
            ip = request.getHeader("WL-Proxy-Client-IP");   
        }   
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
            ip = request.getRemoteAddr();   
            if(ip.equals("127.0.0.1")){     
                //根据网卡取本机配置的IP     
                InetAddress inet=null;     
                try {     
                    inet = InetAddress.getLocalHost();     
                } catch (Exception e) {     
                    e.printStackTrace();     
                }     
                ip= inet.getHostAddress();     
            }  
        }   
        // 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割  
        if(ip != null && ip.length() > 15){    
            if(ip.indexOf(",")>0){     
                ip = ip.substring(0,ip.indexOf(","));     
            }     
        }     
        return ip;   
    }
    
    public static String getMACAddress(String ip) throws Exception {  
        String line = "";  
        String macAddress = "";  
        final String MAC_ADDRESS_PREFIX = "MAC Address = ";  
        final String LOOPBACK_ADDRESS = "127.0.0.1";  
        //如果为127.0.0.1,则获取本地MAC地址。  
        if (LOOPBACK_ADDRESS.equals(ip)) {  
            InetAddress inetAddress = InetAddress.getLocalHost();  
            //貌似此方法需要JDK1.6。  
            byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();  
            //下面代码是把mac地址拼装成String  
            StringBuilder sb = new StringBuilder();  
            for (int i = 0; i < mac.length; i++) {  
                if (i != 0) {  
                    sb.append("-");  
                }  
                //mac[i] & 0xFF 是为了把byte转化为正整数  
                String s = Integer.toHexString(mac[i] & 0xFF);  
                sb.append(s.length() == 1 ? 0 + s : s);  
            }  
            //把字符串所有小写字母改为大写成为正规的mac地址并返回  
            macAddress = sb.toString().trim().toUpperCase();  
            return macAddress;  
        }  
        //获取非本地IP的MAC地址  
        try {  
            Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);  
            InputStreamReader isr = new InputStreamReader(p.getInputStream());  
            BufferedReader br = new BufferedReader(isr);  
            while ((line = br.readLine()) != null) {  
                if (line != null) {  
                    int index = line.indexOf(MAC_ADDRESS_PREFIX);  
                    if (index != -1) {  
                        macAddress = line.substring(index + MAC_ADDRESS_PREFIX.length()).trim().toUpperCase();  
                    }  
                }  
            }  
            br.close();  
        } catch (IOException e) {  
            e.printStackTrace(System.out);  
        }  
        return macAddress;  
    }
    
    //获取本机的Mac地址
    public static String GetMac(){
    	InetAddress ia;
    	byte[] mac = null;
    	try {
    		//获取本地IP对象
    		ia = InetAddress.getLocalHost();
    		//获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。  
    		mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();  
    	} catch (Exception e) {
    	  // TODO Auto-generated catch block
    		e.printStackTrace();
    	}
        //下面代码是把mac地址拼装成String  
        StringBuffer sb = new StringBuffer();  
        for(int i=0;i<mac.length;i++){  
        	if(i!=0){  
        		sb.append("-");  
        	}  
        	//mac[i] & 0xFF 是为了把byte转化为正整数  
        	String s = Integer.toHexString(mac[i] & 0xFF);  
        	sb.append(s.length()==1?0+s:s);  
        }  
        //把字符串所有小写字母改为大写成为正规的mac地址并返回  
        return sb.toString().toUpperCase();
    }
    
	public static String getMac(String ip){
		String str = null;
		String mac = null;
		try{
			Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);  
			InputStreamReader ir = new InputStreamReader(p.getInputStream(),"gbk");  
			LineNumberReader input = new LineNumberReader(ir);  
			for (; true;) {  
				str = input.readLine(); 
				if (str != null) {
					if (str.indexOf("MAC 地址") > 1) {
						mac = str.substring(str.indexOf("MAC 地址") + 9);
						break; 
					}
				}
			}
			System.out.println(mac);
		}catch(IOException e){
			e.printStackTrace();
		}
		return mac;
	}
	/**
	 * 校验手机imei 返回0则校验成功
	 * @param code
	 * @return
	 */
	public static String checkPhoneImei(String code) {
		int total = 0, sum1 = 0, sum2 = 0;
		int temp = 0;
		char[] chs = code.toCharArray();
		for (int i = 0; i < chs.length; i++) {
			int num = chs[i] - '0';
			// ascii to num
			// System.out.println(num);
			/* (1)将奇数位数字相加(从1开始计数) */
			if (i % 2 == 0) {
				sum1 = sum1 + num;
			} else {
				/* (2)将偶数位数字分别乘以2,分别计算个位数和十位数之和(从1开始计数) */
				temp = num * 2;
				if (temp < 10) {
					sum2 = sum2 + temp;
				} else {
					sum2 = sum2 + temp + 1 - 10;
				}
			}
		}
		total = sum1 + sum2;
		/* 如果得出的数个位是0则校验位为0,否则为10减去个位数 */
		if (total % 10 == 0) {
			return "0";
		} else {
			return (10 - (total % 10)) + "";
		}
	}
	
	public static boolean checkTimeFrame(String startTime,String endTime) throws Exception{
		boolean bool=false;
		//设置时间格式
		SimpleDateFormat sDateFormat=new SimpleDateFormat("HH:mm:ss"); 
		Calendar date = Calendar.getInstance();
		Calendar after = Calendar.getInstance();
		Calendar before = Calendar.getInstance();
		//当前时间
	    String systemTime=sDateFormat.format(new Date());
		Date startTimeDate=sDateFormat.parse(startTime.toString());
		Date endStringDate=sDateFormat.parse(endTime.toString());
		Date systemTimeDate=sDateFormat.parse(systemTime);		
        date.setTime(systemTimeDate);   
        after.setTime(startTimeDate);
        before.setTime(endStringDate);
        //判断当前时间是否在开始和结束时间之内
        if (date.after(after) && date.before(before)) 
        	bool=true;
        return bool;
	}

	
//	public static void getFiledome(File file) throws LineUnavailableException, UnsupportedAudioFileException, IOException {
//		Encoder encoder = new Encoder();
//        String length = "";
//        try {
//            MultimediaInfo m = encoder.getInfo(file);
//            System.out.println("-------"+m.getDuration());
//            long ls = m.getDuration()/1000;
//            int hour = (int) (ls/3600);
//            int minute = (int) (ls%3600)/60;
//            int second = (int) (ls-hour*3600-minute*60);
//            length = "视频时长为："+hour+"时"+minute+"分"+second+"秒";
//            System.out.println(length);
//            System.out.println("此视频高度为:" + m.getVideo().getSize().getHeight());
//
//            System.out.println("此视频宽度为:" + m.getVideo().getSize().getWidth());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//		
//	}
}
